<template>
  <div class="finance-reports-container">
    <!-- 时间范围筛选 -->
    <div class="filter-section">
      <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
        <el-radio-button label="daily">每日</el-radio-button>
        <el-radio-button label="monthly">每月</el-radio-button>
        <el-radio-button label="annual">每年</el-radio-button>
      </el-radio-group>

      <!-- 每日和每月模式：单个日期选择器 -->
      <el-date-picker v-model="selectedDate" style="width: 250px;" :type="datePickerType" :placeholder="datePlaceholder"
        :format="dateFormat" :value-format="valueFormat" @change="handleDateChange" class="date-picker"
        :picker-options="pickerOptions" :clearable="false" v-if="timeRange !== 'annual'" />

      <!-- 每年模式：年份范围选择器 -->
      <div v-if="timeRange === 'annual'" class="year-range-picker">
        <el-date-picker v-model="startYear" type="year" placeholder="开始年份" format="YYYY年" value-format="YYYY"
          style="width: 120px;" :picker-options="startYearPickerOptions" @change="handleYearRangeChange" />
        <span style="margin: 0 10px;">至</span>
        <el-date-picker v-model="endYear" type="year" placeholder="结束年份" format="YYYY年" value-format="YYYY"
          style="width: 120px;" :picker-options="endYearPickerOptions" @change="handleYearRangeChange" />
      </div>

      <div v-if="timeRange === 'daily'" class="date-tip">
        显示 {{ currentMonth }} 的每日数据
      </div>
      <div v-else-if="timeRange === 'monthly'" class="date-tip">
        显示 {{ currentYear }} 年的每月数据
      </div>
      <div v-else-if="timeRange === 'annual'" class="date-tip">
        显示 {{ startYear }} - {{ endYear }} 年的年度数据
      </div>
    </div>

    <!-- 组合图表展示区 -->
    <div class="chart-area">
      <div class="chart-wrapper">
        <div class="chart-header">
          <h3>REV与订单数量以及销量分析</h3>
          <el-tooltip content="显示REV(柱状图)和订单数量(折线图)的组合数据" placement="top">
            <el-icon>
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
        <div ref="combinedChart" class="chart-content" v-loading="loading"></div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <el-table :data="tableData" border stripe v-loading="loading" :empty-text="emptyText" height="500">
        <el-table-column prop="date" :label="timeRangeText" width="120" fixed />
        <el-table-column prop="rev" label="REV(元)" width="150" align="right">

          <template #default="{ row }">
            {{ formatCurrency(row.rev) }}
          </template>
        </el-table-column>
        <el-table-column prop="active_count" label="激活订单数" width="120" align="center" />
        <el-table-column prop="sale_quantity" label="销售数量" width="120" align="center" />
        <el-table-column label="环比变化" width="150" align="center">
          <template #default="{ row }">
            <span :class="getChangeClass(row.revChange)">
              {{ row.revChange !== null ? `${row.revChange}%` : '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>




 
<script>
import { use } from 'echarts/core'
import { LineChart, BarChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import * as echarts from 'echarts'
import { debounce } from 'lodash'
import { markRaw } from 'vue'

use([LineChart, BarChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer])
import {
  orderstats_dailyAPI,
  orderstats_monthlyAPI,
  orderstats_annualAPI
} from '@/api/api'
import dayjs from 'dayjs'
import { QuestionFilled } from '@element-plus/icons-vue'

export default {
  name: 'FinanceReports',
  components: { QuestionFilled },
  data() {
    const currentYear = dayjs().year().toString()
    const startYear = (dayjs().year() - 4).toString() // 默认显示过去5年

    return {
      timeRange: 'daily',
      selectedDate: dayjs().format('YYYYMM'), // 默认选择当前月份
      startYear: startYear, // 年度模式开始年份
      endYear: currentYear, // 年度模式结束年份
      loading: false,
      emptyText: '暂无数据',
      tableData: [],
      combinedChart: null,
      chartData: {
        dates: [],
        revData: [],
        countData: [],
        quantityData: []
      }
    }
  },
  computed: {
    timeRangeText() {
      return {
        daily: '日期',
        monthly: '月份',
        annual: '年份'
      }[this.timeRange]
    },
    currentMonth() {
      return dayjs(this.selectedDate).format('YYYY年MM月')
    },
    currentYear() {
      return dayjs(this.selectedDate).format('YYYY年')
    },
    datePickerType() {
      if (this.timeRange === 'annual') {
        return 'year'
      } else if (this.timeRange === 'monthly') {
        return 'year'
      } else {
        return 'month'
      }
    },
    datePlaceholder() {
      if (this.timeRange === 'annual') {
        return '选择年份'
      } else if (this.timeRange === 'monthly') {
        return '选择年份'
      } else {
        return '选择年月'
      }
    },
    dateFormat() {
      if (this.timeRange === 'annual') {
        return 'YYYY年'
      } else if (this.timeRange === 'monthly') {
        return 'YYYY年'
      } else {
        return 'YYYY年MM月'
      }
    },
    valueFormat() {
      if (this.timeRange === 'annual') {
        return 'YYYY'
      } else if (this.timeRange === 'monthly') {
        return 'YYYY'
      } else {
        return 'YYYYMM'
      }
    },
    apiMethod() {
      return this.timeRange === 'annual' ? orderstats_annualAPI :
        this.timeRange === 'monthly' ? orderstats_monthlyAPI : orderstats_dailyAPI
    },
    dateField() {
      return this.timeRange === 'annual' ? 'year_str' :
        this.timeRange === 'monthly' ? 'month_str' : 'date_str'
    },
    pickerOptions() {
      const currentYear = dayjs().year()
      const currentMonth = dayjs().format('YYYYMM')

      if (this.timeRange === 'daily') {
        return {
          disabledDate: (time) => {
            const timeYear = dayjs(time).year()
            const timeMonth = dayjs(time).format('YYYYMM')
            return timeMonth > currentMonth
          }
        }
      } else {
        return {
          disabledDate: (time) => {
            const timeYear = dayjs(time).year()
            return timeYear > currentYear || timeYear < (currentYear - 9)
          }
        }
      }
    },
    // 开始年份选择器选项
    startYearPickerOptions() {
      const currentYear = dayjs().year()
      return {
        disabledDate: (time) => {
          const timeYear = dayjs(time).year()
          // 开始年份不能大于结束年份，不能大于当前年份
          return timeYear > currentYear || (this.endYear && timeYear > parseInt(this.endYear))
        }
      }
    },
    // 结束年份选择器选项
    endYearPickerOptions() {
      const currentYear = dayjs().year()
      return {
        disabledDate: (time) => {
          const timeYear = dayjs(time).year()
          // 结束年份不能小于开始年份，不能大于当前年份
          return timeYear > currentYear || (this.startYear && timeYear < parseInt(this.startYear))
        }
      }
    }
  },
  mounted() {
    this.initCharts()
    this.fetchData()
    this.addResizeListener()
  },
  beforeUnmount() {
    this.removeResizeListener()
    this.disposeCharts()
  },
  methods: {
    initCharts() {
      try {
        // 使用markRaw避免ECharts实例被Vue响应式代理
        this.combinedChart = markRaw(echarts.init(this.$refs.combinedChart))
        // 添加错误监听器来捕获ECharts内部错误
        this.combinedChart.on('error', (error) => {
          console.error('ECharts图表错误:', error)
          this.handleChartError()
        })
        this.renderEmptyCharts()
      } catch (error) {
        console.error('图表初始化失败:', error)
        this.handleChartError()
      }
    },

    handleChartError() {
      // 显示错误提示
      this.emptyText = '图表渲染异常，请刷新页面重试'
      // 清除图表实例
      this.combinedChart?.dispose()
      this.combinedChart = null
    },

    renderEmptyCharts() {
      const emptyOption = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: { color: '#999' }
        },
        xAxis: { show: false },
        yAxis: { show: false }
      }
      this.combinedChart.setOption(emptyOption, true)
    },

    addResizeListener() {
      window.addEventListener('resize', this.handleResize)
    },

    removeResizeListener() {
      window.removeEventListener('resize', this.handleResize)
    },

    handleResize: debounce(function () {
      this.combinedChart?.resize()
    }, 300),

    disposeCharts() {
      this.combinedChart?.dispose()
    },

    async fetchData() {
      this.loading = true
      this.emptyText = '数据加载中...'

      try {
        let params = {}
        if (this.timeRange === 'daily') {
          params = {
            month: this.selectedDate
          }
        } else if (this.timeRange === 'monthly') {
          params = {
            year: this.selectedDate
          }
        } else {
          // 每年模式：使用开始年份和结束年份
          if (!this.startYear || !this.endYear) {
            this.$message.warning('请选择开始年份和结束年份')
            return
          }
          params = {
            startYear: this.startYear,
            endYear: this.endYear
          }
        }


        const response = await this.apiMethod(params)
        const data = response.data || response
        console.log('API 返回数据:', data) // 添加这行查看原始数据
        if (data && data.length) {
          this.processChartData(data)
          this.renderCharts()
          this.processTableData(data)
        } else {
          this.emptyText = '暂无数据'
          this.clearChartsAndData()
        }
      } catch (error) {
        console.error('数据获取失败:', error)
        this.$message.error('数据获取失败，请稍后重试')
        this.emptyText = '数据加载失败'
        this.clearChartsAndData()
      } finally {
        this.loading = false
      }
    },

    clearChartsAndData() {
      this.chartData = {
        dates: [],
        revData: [],
        countData: [],
        quantityData: []
      }
      this.tableData = []
      this.renderEmptyCharts()
    },

    handleDateChange() {
      this.clearChartsAndData()
      this.fetchData()
    },

    // 处理年份范围变化
    handleYearRangeChange() {
      if (this.startYear && this.endYear) {
        this.clearChartsAndData()
        this.fetchData()
      }
    },

    handleTimeRangeChange() {
      if (this.timeRange === 'annual') {
        // 年度模式：设置默认的年份范围（过去5年）
        const currentYear = dayjs().year().toString()
        this.startYear = (dayjs().year() - 4).toString()
        this.endYear = currentYear

        // 延迟一下确保数据已经更新
        this.$nextTick(() => {
          this.clearChartsAndData()
          this.fetchData()
        })
      } else if (this.timeRange === 'monthly') {
        this.selectedDate = dayjs().format('YYYY')
        this.clearChartsAndData()
        this.fetchData()
      } else {
        this.selectedDate = dayjs().format('YYYYMM')
        this.clearChartsAndData()
        this.fetchData()
      }
    },

    processChartData(data) {
      // 确保数据是数组格式
      const validData = Array.isArray(data) ? data : [];
      
      if (this.timeRange === 'daily') {
        const yearMonth = this.selectedDate
        const daysInMonth = dayjs(this.selectedDate).daysInMonth()

        const fullDates = Array.from({ length: daysInMonth }, (_, i) => {
          const day = (i + 1).toString().padStart(2, '0')
          return `${yearMonth}${day}`
        })

        const dataMap = new Map()
        validData.forEach(item => {
          if (item && item.date_str) {
            dataMap.set(item.date_str, item)
          }
        })

        const mergedData = fullDates.map(date => {
          const apiData = dataMap.get(date)
          return apiData ? {
            ...apiData,
            date_str: date
          } : {
            date_str: date,
            active_count: 0,
            rev: 0,
            sale_quantity: 0
          }
        })

        this.chartData.dates = mergedData.map(item => {
          return item.date_str.substring(6) + '日'
        })

        this.chartData.revData = mergedData.map(item => {
          return Number(item.dailyRev || item.rev || item.totalRev || item.amount || 0)
        })

        this.chartData.countData = mergedData.map(item => Number(item.active_count || 0))
        this.chartData.quantityData = mergedData.map(item => Number(item.sale_quantity || 0))
      } else {
        // 确保数据有正确的字段
        const sortedData = [...validData].filter(item => item && item[this.dateField]).sort((a, b) => {
          return a[this.dateField].localeCompare(b[this.dateField])
        })

        this.chartData.dates = sortedData.map(item => {
          if (this.timeRange === 'annual') {
            return item.year_str + '年'
          } else if (this.timeRange === 'monthly') {
            return item.month_str.substring(0, 4) + '年' + item.month_str.substring(4) + '月'
          }
          return item.date_str.substring(6) + '日'
        })

        this.chartData.revData = sortedData.map(item => {
          return Number(item.annualRev || item.monthlyRev || item.dailyRev || item.rev || 0)
        })

        this.chartData.countData = sortedData.map(item => {
          return Number(item.annualactive_count || item.monthlyactive_count || item.active_count || 0)
        })
        this.chartData.quantityData = sortedData.map(item => Number(item.sale_quantity || 0))
      }
      
      // 确保所有数据都是有效的数字数组
      this.chartData.revData = this.chartData.revData.map(val => isNaN(val) ? 0 : val);
      this.chartData.countData = this.chartData.countData.map(val => isNaN(val) ? 0 : val);
      this.chartData.quantityData = this.chartData.quantityData.map(val => isNaN(val) ? 0 : val);
    },



    renderCharts() {
      // 如果图表实例不存在，重新初始化
      if (!this.combinedChart) {
        this.initCharts()
        return
      }

      const isMonthly = this.timeRange === 'monthly';
      const isAnnual = this.timeRange === 'annual';
      const dataLength = this.chartData.dates.length
      const barWidth = '90%'
      const labelInterval = dataLength > 30 ? 5 :
        dataLength > 14 ? 2 :
          dataLength >= 5 ? 1 : 0;

      // 确保数据有效性
      const validDates = this.chartData.dates || [];
      const validRevData = this.chartData.revData || [];
      const validCountData = this.chartData.countData || [];
      const validQuantityData = this.chartData.quantityData || [];

      // 如果数据为空，显示空状态
      if (validDates.length === 0 || validRevData.length === 0) {
        this.renderEmptyCharts()
        return
      }

      const option = {
        // 明确指定图表类型，避免极坐标布局计算
        series: [
          {
            name: 'REV',
            type: 'bar',
            coordinateSystem: 'cartesian2d', // 明确使用笛卡尔坐标系
            barWidth: barWidth,
            data: validRevData,
            itemStyle: {
              color: 'rgba(232, 152, 32, 0.86)',
              borderRadius: [4, 4, 0, 0]
            },
            label: {
              show: dataLength <= 31,
              position: 'top',
              formatter: params => {
                const value = params.value
                return value >= 10000
                  ? `${(value / 10000).toFixed(1)}万`
                  : value.toLocaleString()
              },
              fontSize: 12
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          },
          {
            name: '订单数量',
            type: 'line',
            coordinateSystem: 'cartesian2d', // 明确使用笛卡尔坐标系
            legendHoverLink: false,
            yAxisIndex: 1,
            data: validCountData,
            symbol: 'triangle',
            symbolSize: 8,
            itemStyle: {
              color: '#67C23A'
            },
            lineStyle: {
              width: 1
            },
            label: {
              show: dataLength <= 31,
              position: 'top',
              offset: [5, 30],
              fontSize: 12
            }
          },
          {
            name: '销售数量',
            type: 'line',
            coordinateSystem: 'cartesian2d', // 明确使用笛卡尔坐标系
            yAxisIndex: 2,
            legendHoverLink: false,
            data: validQuantityData,
            symbol: 'diamond',
            symbolSize: 8,
            itemStyle: {
              color: '#A483FF'
            },
            lineStyle: {
              color: '#A483FF',
              width: 1
            },
            label: {
              show: dataLength <= 31,
              position: 'top',
              offset: [5, 30],
              fontSize: 12
            }
          }
        ],
        tooltip: {
          trigger: 'axis', // 使用axis而不是cross，避免复杂的交叉指针
          axisPointer: {
            type: 'line', // 使用line而不是cross
            lineStyle: {
              color: '#00f'
            }
          },
          formatter: params => {
            let result = params[0].axisValue + '<br/>'
            params.forEach(item => {
              if (item.seriesName === 'REV') {
                result += `${item.marker}  ${item.seriesName}:  ${this.formatCurrency(item.value)}<br/>`
              } else {
                result += `${item.marker}  ${item.seriesName}:  ${item.value.toLocaleString()}<br/>`
              }
            })
            return result
          }
        },
        legend: {
          data: ['REV', '订单数量', '销售数量'],
          selected: {
            'REV': true,       // 默认显示柱状图
            '订单数量': false,  // 默认隐藏订单数量折线图 
            '销售数量': false   // 默认隐藏销售数量折线图
          },
          top: 0,
        },
        xAxis: {
          type: 'category',
          data: validDates,
          axisPointer: {
            type: 'shadow'
          },
          axisLabel: {
            rotate: 30,
            interval: labelInterval,
            fontSize: 12,
          },
          offset: 10,
        },
        yAxis: [
          {
            type: 'value',
            name: '金额(元)',
            min: 0,
            max: isAnnual ? 500000 : isMonthly ? 50000 : 5000,
            axisLabel: {
              formatter: value => value >= 10000 ? `${(value / 10000).toFixed(1)}万` : value
            }
          },
          {
            type: 'value',
            name: '订单数',
            min: 0,
            max: isAnnual ? 1000 : isMonthly ? 100 : 10,
            position: 'right',
            axisLabel: {
              formatter: value => value >= 10000 ? `${(value / 10000).toFixed(1)}万` : value
            }
          },
          {
            type: 'value',
            name: '销售数量',
            min: 0,
            max: isAnnual ? 20000 : isMonthly ? 2000 : 200,
            position: 'right',
            offset: 50,  // 向右偏移避免重叠 
            axisLabel: {
              formatter: value => value >= 10000 ? `${(value / 10000).toFixed(1)}万` : value
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      }

      try {
        this.combinedChart.setOption(option, true)
        this.handleResize()
      } catch (error) {
        console.error('图表渲染错误:', error)
        // 如果渲染失败，显示错误提示
        this.combinedChart.setOption({
          title: {
            text: '图表渲染失败',
            subtext: '请检查数据格式',
            left: 'center',
            top: 'center',
            textStyle: { color: '#f56c6c' }
          },
          xAxis: { show: false },
          yAxis: { show: false }
        }, true)
      }
    },

    processTableData(data) {
      const sourceData = this.timeRange === 'daily'
        ? this.chartData.dates.map((date, index) => ({
          date_str: this.selectedDate + date.replace(' 日', '').padStart(2, '0'),
          dailyRev: this.chartData.revData[index],
          active_count: this.chartData.countData[index],
          sale_quantity: this.chartData.quantityData[index] || 0 // 确保包含销售数量 
        }))
        : data

      const sortedData = [...sourceData].sort((a, b) => {
        return b[this.dateField]?.localeCompare(a[this.dateField])
      })

      this.tableData = sortedData.map((item, index) => {
        const prevItem = sortedData[index + 1]
        let revChange = null

        if (prevItem) {
          const currentRev = this.timeRange === 'annual' ? (item.annualRev || item.rev) :
            this.timeRange === 'monthly' ? (item.monthlyRev || item.rev) : (item.dailyRev || item.rev)
          const prevRev = this.timeRange === 'annual' ? (prevItem.annualRev || prevItem.rev) :
            this.timeRange === 'monthly' ? (prevItem.monthlyRev || prevItem.rev) : (prevItem.dailyRev || prevItem.rev)

          revChange = prevRev === 0 ? null :
            ((currentRev - prevRev) / prevRev * 100).toFixed(2)
        }

        return {
          date: this.formatTableDate(item[this.dateField] || item.date_str || item.dateStr),
          rev: this.timeRange === 'annual' ? (item.annualRev || item.rev) :
            this.timeRange === 'monthly' ? (item.monthlyRev || item.rev) : (item.dailyRev || item.rev),
          active_count: item.active_count || 0, // 简化处理，统一使用active_count 
          sale_quantity: item.sale_quantity || 0,
          revChange,
          rawData: item
        }
      })

      console.log(' 处理后的表格数据:', this.tableData)  // 调试用 
    },

    formatTableDate(date_str) {
      if (this.timeRange === 'annual') {
        return `${date_str}年`
      } else if (this.timeRange === 'monthly') {
        return `${date_str.substring(0, 4)}-${date_str.substring(4)}`
      } else {
        return `${date_str.substring(0, 4)}-${date_str.substring(4, 6)}-${date_str.substring(6)}`
      }
    },

    formatCurrency(value) {
      if (value === null || value === undefined) return '-'
      return new Intl.NumberFormat('zh-CN', {
        style: 'decimal',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(value)
    },

    getChangeClass(value) {
      if (value === null) return ''
      const num = parseFloat(value)
      if (num > 0) return 'positive-change'
      if (num < 0) return 'negative-change'
      return ''
    },

    handleDetail(row) {
      this.$message.info(`查看 ${row.date} 的详细数据`)
      console.log('详情数据:', row.rawData)
    }
  }
}
</script>





 
<style lang="scss" scoped>
.finance-reports-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.filter-section {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;

  .date-picker {
    margin-left: 20px;
  }

  .year-range-picker {
    margin-left: 20px;
    display: flex;
    align-items: center;
  }

  .date-tip {
    margin-left: 15px;
    color: #666;
    font-size: 14px;
  }
}

.chart-area {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-wrapper {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .chart-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: bold;
    }

    .el-icon {
      margin-left: 8px;
      color: #909399;
      cursor: pointer;
    }
  }

  .chart-content {
    height: 500px;
    width: 100%;
  }
}

.data-table {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;

  :deep(.el-table) {
    .positive-change {
      color: #f56c6c;
      font-weight: bold;
    }

    .negative-change {
      color: #67c23a;
      font-weight: bold;
    }
  }
}

:deep(.echarts-series) {
  &.sales-quantity {
    .echarts-series-name {
      color: #409EFF;
    }
  }
}
</style>